<!-- 智能补货分析 -->
<template>
  <div class="basic_info" ref="basicView">
    <div class="top-view" ref="topView">
      <div class="info_operation_btn">
        <div class="btn_left">
          <el-button type="primary" @click="onHandleAnalyse()" style="font-weight: 500">补货分析</el-button>
          <div class="pretend_view" @click="onAddGoods">添加商品</div>
          <div class="pretend_view" @click="onDelGoods">删除商品</div>
          <el-popover placement="bottom" width="100" trigger="click" v-model="popVisible">
            <div style="line-height: 30px">
              <div @click="onCreateBill('1')">生成采购订单</div>
              <div style="margin: 5px 0; width: 100%; height: 1px; background-color: #ededed"></div>
              <div @click="onCreateBill('2')">生成采购入库单</div>
            </div>
            <div slot="reference" class="pretend_view">
              <span style="margin-right: 6px">生成单据</span>
              <i class="el-icon-arrow-down"></i>
            </div>
          </el-popover>
          <div class="pretend_view" @click="onLocationRecord">定位记录</div>
          <div class="pretend_view" @click="onPrint">打印</div>
          <el-checkbox v-model="queryData.isConsiderPending" style="line-height: 30px; margin-left: 5px"
            >考虑待审核数量</el-checkbox
          >
          <el-checkbox v-model="queryData.isConsiderPendingOrder" style="line-height: 30px; margin-left: 5px"
            >考虑待执行订单数量</el-checkbox
          >
          <el-button type="primary" @click="onHandleResetAnalyse(true)" style="font-weight: 500">重新计算</el-button>
        </div>
        <div class="btn_right">
          <!-- <el-input v-model="queryData.queryParam" placeholder="请输入商品名称\条码\编码\规格\拼音码"></el-input>
          <el-button type="primary" @click="onQuery">搜索</el-button>
          <el-button @click="onRefresh">刷新</el-button> -->
          <i @click="onShowColumn" class="set_up el-icon-s-tools"></i>
        </div>
      </div>
      <div class="info_operation_btn">
        <div class="btn_left">
          <div>
            <span style="margin: 0 10px">某段时间的最近采购价</span>
            <el-date-picker
              size="small"
              style="width: 240px"
              v-model="dateValue"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="dateChange"
            >
            </el-date-picker>
          </div>
          <div>
            <span style="margin: 0 10px">补货仓库</span>
            <el-select v-model="queryData.storehouseId" placeholder="请选择" size="small" style="width: 170px">
              <el-option v-for="item in storehouseOptions" :key="item.id" :label="item.storehouseName" :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div>
            <span style="margin: 0 10px">补货方式</span>
            <el-select v-model="queryData.replenishmentType" placeholder="请选择" size="small" style="width: 170px">
              <el-option
                v-for="item in replenishmentTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <div>
            <span style="margin: 0 10px">所属供应商</span>
            <el-select
              v-model="queryData.companyId"
              filterable
              placeholder="请选择"
              size="small"
              style="width: 170px"
              clearable
              @change="getTableData(1)"
            >
              <el-option v-for="item in companyOptions" :key="item.id" :label="item.companyName" :value="item.id">
              </el-option>
            </el-select>
          </div>

          <div class="pretend_view" @click="onBatchSet" style="padding: 0 20px; margin-left: 10px">
            设置采购量为建议采购量
          </div>
        </div>
      </div>
    </div>
    <div class="info_content_div" :style="{ height: topHeight + 'px' }">
      <div class="div_tree">
        <div class="tree_div1">商品类别</div>
        <div class="tree_input">
          <p>
            <input type="text" placeholder="查找" v-model="filterText" />
            <span>
              <i class="el-icon-search"></i>
            </span>
          </p>
        </div>
        <div class="tree_structure">
          <el-tree
            ref="tree"
            :data="treeData"
            node-key="id"
            :props="defaultProps"
            highlight-current
            :default-expand-all="treeExpandAll"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            :filter-node-method="filterNode"
          >
            <span class="tree_node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span v-if="!data.id" style="color: #1c94fa" @click.stop="treeExpandChange">{{
                treeExpandAll ? '全部收缩' : '全部展开'
              }}</span>
            </span>
          </el-tree>
        </div>
      </div>
      <div class="div_table">
        <div class="table_content">
          <div style="width: max-content; height: 100%">
            <el-table
              ref="table"
              :data="tableData"
              height="100%"
              border
              tooltip-effect="dark"
              highlight-current-row
              :header-cell-style="{
                fontSize: '12px',
                background: '#E3F6FF',
                color: '#666666',
                textAlign: 'center',
                height: '30px',
                borderColor: '#dddddd',
              }"
              show-summary
              :summary-method="getSummaries"
              @selection-change="handleSelectionChange"
              @header-dragend="onHandleDrag"
            >
              <el-table-column>
                <template slot="header">
                  <div
                    style="width: 100%; height: 100%; background-color: white; line-height: 30px"
                    @click="handleInvert"
                  >
                    反选
                  </div>
                </template>
                <el-table-column type="selection"></el-table-column>
              </el-table-column>
              <el-table-column
                v-for="(item1, index1) in columnData.filter((el) => el.show)"
                :key="index1"
                :label="item1.label"
              >
                <el-table-column v-if="index1 == 0" label="序号" type="index" width="50"> </el-table-column>
                <template v-for="(item, i) in item1.subset">
                  <el-table-column
                    :key="i"
                    :show-overflow-tooltip="
                      !['purchaseNumber', 'purchasePrice', 'suggestPlanProductionNumber'].includes(item.props)
                    "
                    :prop="item.props"
                    :label="item.zidingyiName ? item.zidingyiName : item.morenName"
                    v-if="item.zidingyiState"
                    min-width="150px"
                    border
                    :resizable="item.props=='goodsName'?true:false"
                    :width="item.cellWidth"
                  >
                    <template slot-scope="scope">
                      <span v-if="item.props == 'purchaseNumber'">
                        <el-input
                          type="text"
                          v-model="scope.row[item.props]"
                          onkeyup="value=value.replace(/[^\d.]/g,'')"
                          @blur="handlePurchaseNumberBlur(scope.$index, scope.row)"
                          @focus="inputFocus($event)"
                          placeholder="请输入"
                        />
                      </span>
                      <span v-else-if="item.props == 'purchasePrice'">
                        <el-input
                          type="text"
                          v-model="scope.row[item.props]"
                          onkeyup="value=value.replace(/[^\d.]/g,'')"
                          @blur="handlePurchaseNumberBlur(scope.$index, scope.row)"
                          @focus="inputFocus($event)"
                          placeholder="请输入"
                        />
                      </span>
                      <span v-else-if="item.props == 'goodsName'" style="width: 100%; white-space: normal;
  word-wrap: break-word;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;">{{  scope.row[item.props]  }}</span>
                      <span v-else-if="['opNumber','pending','userNumber','purchaseOrder','productionOrder','salesOrder','planNumber'].includes(item.props)">{{ $formatNumber(scope.row[item.props]) }} </span>
                      <span v-else>{{ scope.row[item.props] }}</span>
                    </template>
                  </el-table-column>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <!-- <div class="total_record">
          <p>合计</p>
          <p>共{{ dataTotal }}条记录</p>
        </div> -->
        <div class="table_pagination">
          <div class="pagination_div">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[20, 50, 100, 200]"
              :page-size="pagesize"
              layout="jumper, prev, pager,next, sizes"
              :total="dataTotal"
            ></el-pagination>
          </div>
        </div>
      </div>
    </div>
    <!-- 选择商品弹框 -->
    <DialogCommodity
      ref="commodityRef"
      :storehouseId="queryData.storehouseId"
      :companyId="queryData.companyId"
      @onSelectCommodityMultiple="onSelectCommodityMultiple"
    ></DialogCommodity>
    <!-- 列配置弹框 -->
    <CConfiguration
      ref="setColumnRef"
      :columnDataArr="columnData"
      :defaultColumnDataArr="defaultColumnData"
      orderType="智能补货"
      @onSaveColumn="onSaveColumn"
    ></CConfiguration>
    <!-- 提醒弹框 -->
    <PopupReminder ref="reminderRef" :tipsData="tipsData" @dialogVisibleClose="onNo" @onConfirm="onYes"></PopupReminder>
    <!-- 成功弹框 -->
    <PopupSuccess ref="successRef" :tipsData="tipsData"></PopupSuccess>
    <!-- 定位记录 -->
    <div class="location">
      <el-dialog title="定位记录" :visible.sync="extendVisible" width="400px">
        <div class="extendView">
          <el-input
            v-model="filterValue"
            size="small"
            placeholder="请输入商品名称\编码\规格\单位"
            style="width: 100%"
          ></el-input>
        </div>
        <div class="dialog_bottom">
          <el-button size="small" @click.stop="extendVisible = false">取消</el-button>
          <el-button type="primary" size="small" @click.stop="onExtendConfirm">确定</el-button>
        </div>
      </el-dialog>
    </div>
    <dialog-print ref="print"></dialog-print>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import CConfiguration from '@/components/c_column/columnConfiguration1'
import PopupReminder from '../components/popupReminder'
import PopupSuccess from '../components/popupSuccess'
import DialogCommodity from '@/views/components/dialogCommodity'
import dialogPrint from '@/views/components/dialogPrintStatic'
import { getAction, putAction, deleteAction, downPostFile, postAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
// 导入调用处理权限数据方法
import {
  handlePermissions,
  handleOtherPerms,
  delcommafy,
  formatMoney,
  formatNumber,
  formatPrice,
  accMul,
  handlePagePermissions
} from '@/utils/index'
export default {
  inject: ['remove', 'getCurrentPages'],
  name: 'smartReplenish',
  mixins: [JeecgListMixin],
  components: {
    CConfiguration,
    PopupReminder,
    PopupSuccess,
    DialogCommodity,
    dialogPrint,
  },
  computed: {
    buttonsPermissions() {
      return handlePermissions('智能补货分析')
    },
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
      this.$refs.tree1.filter(val)
    },
  },
  data() {
    return {
      queryData: {
        goodsId: '',
        goodType: '', //商品类别
        isConsiderPending: false, //是否考虑待审核数量
        isConsiderPendingOrder: false, //是否考虑待执行订单数量
        purchasePriceStart: '', //某段时间的最近采购价-开始时间
        purchasePriceEnd: '', //某段时间的最近采购价-结束时间
        replenishmentType: '1', //补货方式(1.补货到库存下限。2补货到库存上限。3补货到库存不为0)
        storehouseId: '', //仓库id
        companyId: '', //供应商
      },
      dateValue: [],
      // 传递给弹框的数据
      tipsData: {
        tipsState: '',
        tipsWords: '',
        tipsMark: '',
      },
      dataTotal: 0,
      pagesize: 20, //每页的数据条数
      currentPage: 1, //默认开始页面
      tableData: [],
      storehouseOptions: [],
      companyOptions: [],
      replenishmentTypeOptions: [
        {
          value: '1',
          label: '补货到库存下限',
        },
        {
          value: '2',
          label: '补货到库存上限',
        },
        {
          value: '3',
          label: '补货到库存不为零',
        },
      ],
      // 列配置数据
      defaultColumnData: [],
      columnData: [
        {
          label: '商品信息',
          show: true,
          subset: [
            {
              morenName: '商品名称',
              props: 'goodsName',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '150px',
            },
            {
              morenName: '商品编码',
              props: 'goodsNumber',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '150px',
            },
            {
              morenName: '规格',
              props: 'goodSpecification',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '150px',
            },
            {
              morenName: '单位',
              props: 'baseUnit_dictText',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '80px',
            },
            {
              morenName: '所属供应商',
              props: 'companyName',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '150px',
            },
            {
              morenName: '所属仓库',
              props: 'storehouseName',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '150px',
            },
            {
              morenName: '库存下限',
              props: 'miniStock',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '100px',
            },
            {
              morenName: '库存上限',
              props: 'highStock',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '100px',
            },
          ],
        },
        {
          label: '库存数量',
          show: true,
          subset: [
            {
              morenName: '库存数量',
              props: 'opNumber',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '100px',
            },
            {
              morenName: '待审核数量',
              props: 'pending',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '100px',
            },
            {
              morenName: '可用库存',
              props: 'userNumber',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '100px',
            },
          ],
        },
        {
          label: '待执行订单数量',
          show: true,
          subset: [
            {
              morenName: '采购订单',
              props: 'purchaseOrder',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '100px',
            },
            {
              morenName: '生产订单',
              props: 'productionOrder',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '100px',
            },
            {
              morenName: '销售订单',
              props: 'salesOrder',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '100px',
            },
            {
              morenName: '计划数量',
              props: 'planNumber',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '100px',
            },
          ],
        },
        {
          label: '补货计划',
          show: true,
          subset: [
            {
              morenName: '采购数量',
              props: 'purchaseNumber',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '150px',
            },
            {
              morenName: '最近采购价',
              props: 'purchasePrice',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '150px',
            },
            {
              morenName: '预估采购资金',
              props: 'estimatePurchaseFund',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '150px',
            },
            {
              morenName: '建议计划生产数',
              props: 'suggestPlanProductionNumber',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '100px',
            },
            {
              morenName: '建议采购量',
              props: 'suggestPurchaseNumber',
              zidingyiName: '',
              morenState: true,
              zidingyiState: true,
              noModify: false,
              cellWidth: '100px',
            },
          ],
        },
      ],

      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      batchData: [], // 存储多选的数据
      updateId: '', // 修改列配置时返回的id
      filterText: '',
      url: {
        analyseUrl: '/smartReplenishment/analyse',
        goodsList: '/smartReplenishment/getAnalyseResult',
        api: '智能补货分析',
      },
      treeExpandAll: true,
      editProps: '', //当前编辑的扩展字段名
      popVisible: false,
      extendVisible: false,
      filterValue: '',
      topHeight: 70,
    }
  },
  created() {
    this.selectTitle()
    this.getTreeData()
    this.getWarehouseData()
    this.getCompanyList()
  },
  mounted() {
    this.$nextTick(() => {
      const basic = this.$refs.basicView
      const el = this.$refs.topView
      if (el && basic) {
        this.topHeight = basic.offsetHeight - el.offsetHeight // 或者使用 el.clientHeight
        console.log(this.topHeight)
      }
    })
  },
  methods: {
    dateChange(e, s) {
      if (e && e.length == 2) {
        this.queryData.purchasePriceStart = e[0] + ' 00:00:00'
        this.queryData.purchasePriceEnd = e[1] + ' 23:59:59'
      } else {
        this.queryData.purchasePriceStart = undefined
        this.queryData.purchasePriceEnd = undefined
      }
    },
    // 反选
    handleInvert() {
      console.log(this.batchData)
      let ids = this.batchData.map((item) => {
        return item.id
      })
      this.tableData.forEach((item) => {
        this.$refs.table.toggleRowSelection(item, !ids.includes(item.id))
      })
    },
    onHandleDrag(newWidth, oldWidth) {
      console.log(newWidth)
      console.log(oldWidth)
      // console.log(column);
      // console.log(event);
    },
    // 重新计算
    onHandleResetAnalyse() {
      this.tipsData.tipsWords = '是否根据设置的条件重新计算“建议采购数量”?'
      this.tipsData.tipsMark = 'onResetAnalyse'
      this.$refs.reminderRef.showSmart()
    },
    // 补货分析
    onHandleAnalyse() {
      const loading = this.$loading({
        lock: true,
        text: '正在努力分析中，请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)',
      })
      
      let params = {
        ...this.queryData,
        goodType: (this.queryData.goodsId && this.queryData.goodsId.length > 0) ? '' : this.queryData.goodType
      }
      setTimeout(() => {
        this.queryData.goodsId = ''
      }, 300) 
      postAction(this.url.analyseUrl, params).then((res) => {
        if (res.code === 200) {
          let result = res.result
          if (result) {
            this.getTableData()
          } else {
            this.$message.error('补货分析失败')
            this.clearData()
          }
        } else {
          this.$message.error(res.message)
          this.getTableData()
        }
        loading.close()
      })
    },
    clearData() {
      this.dataTotal = 0
      this.tableData = []
    },
    onCreateBill(type) {
      this.popVisible = false
      if (type == 1 && !handlePagePermissions('采购订单') ) {
          return this.$elMessage.warning('没有权限！')
      }
      if (this.batchData.length == 0) {
        return this.$message.warning('请选择要操作的数据！')
      }
      // let empty = this.batchData.find(item => !item.purchaseNumber)
      // if (empty) {
      //   return this.$message.warning('请设置采购数量')
      // }

      let pageList = this.getCurrentPages()
      for (let index = 0; index < pageList.length; index++) {
        const element = pageList[index];
        if (element.fullPath.includes('from=replenish')) {
          this.remove(element.fullPath)
        } 
      }

      let companys = Array.from(
        new Set(
          this.batchData.map((item) => {
            return item.companyId
          })
        )
      )
      console.log(companys)
      let replenish = {}
      for (let index = 0; index < companys.length; index++) {
        const element = companys[index]
        // let cs = this.batchData.filter((item) => item.companyId == element)
        let cs = this.batchData.filter((item) => {
          item.stype = 'replenish'
          return item.companyId == element
        })
        replenish[element] = cs
      }
      // localStorage.setItem('replenish', replenish)
      this.$lcStorage.set('replenish', replenish)
      for (let index = 0; index < companys.length; index++) {
        const element = companys[index]
        setTimeout(() => {
          this.$router.push({
            path: `/purchaseManage/purchaseBill/${type == 1 ? 'billPurchaseOrder' : 'billPurchaseWarehousing'}`,
            query: {
              id: element,
              from: 'replenish',
            },
          })
        }, 300)
      }
    },
    // 添加商品
    onAddGoods() {
      this.$refs.commodityRef.goodIds = []
      this.$refs.commodityRef.dialogVisible = true
    },
    // 删除商品
    onDelGoods() {
      if (this.batchData.length == 0) {
        return this.$message.warning('未选择要操作的数据！')
      }
      let ids = this.batchData
        .map((item) => {
          return item.id
        })
        .join(',')
      getAction('/smartReplenishment/deleteById', { id: ids }).then((res) => {
        if (res.code === 200) {
          this.$message.error('删除成功')
          this.getTableData()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 用建议采购数量覆盖采购数量
    onBatchSet() {
      if (this.tableData.length == 0) {
        return this.$message.warning('没有可操作数据！')
      }
      this.tipsData.tipsWords = '是否批量将“采购数量”设置为“建议采购数量”?'
      this.tipsData.tipsMark = 'onCoverPurchaseNumber'
      this.$refs.reminderRef.showSmart()
    },
    // 定位记录
    onLocationRecord() {
      this.filterValue = ''
      this.extendVisible = true
    },
    //定位记录确认
    onExtendConfirm() {
      if (!this.filterValue) {
        return this.$message.warning('请输入要定位的信息')
      }
      let list = this.tableData
      this.tableData = list.filter((item) => {
        return (
          (item.goodsName && item.goodsName.includes(this.filterValue)) ||
          (item.goodsNumber && item.goodsNumber.includes(this.filterValue)) ||
          (item.goodSpecification && item.goodSpecification.includes(this.filterValue)) ||
          (item.baseUnit_dictText && item.baseUnit_dictText.includes(this.filterValue))
        )
      })
      console.log(this.tableData)
      this.extendVisible = false
    },
    // 打印
    async onPrint() {
      if (!this.buttonsPermissions.DaYin) {
        return this.$elMessage.warning('未拥有打印权限！')
      }
      if (this.batchData.length == 0) {
        return this.$elMessage.warning('请选择要打印的数据！')
      }
      // let printExclusive = []
      // let params = {
      //   goodsTypeIds: this.queryData.goodType,
      //   pageSize: this.dataTotal,
      //   pageNo: 1,
      // }
      // let res = await getAction(this.url.goodsList, params)
      // if (res.code === 200) {
      //   printExclusive = res.result.records || []
      // }

      // this.onQuery()
      // // 打印
      // if (!this.buttonsPermissions.DaYin) {
      //   this.$elMessage.warning('未拥有打印权限！')
      // } else if (!printExclusive || printExclusive.length <= 0) {
      //   this.$elMessage.warning('没有要打印的记录！')
      // } else {
      let printData = {
        riqi: this.queryData.purchasePriceStart + '~' + this.queryData.purchasePriceEnd,
        // cangku: this.$refs.cangku.selected.label,
        printExclusive: this.batchData,
      }
      this.$refs.print.show(printData, this.columnData, '智能补货')
      // 可以多次打印设置
      // if (this.printPermissions) {
      //   this.$refs.print.show(printData, this.columnData, this.billName)
      // } else {
      //   if (this.$lcStorage.get('printLimitValue')) {
      //     // 获取打印次数
      //     this.getPrintNum(this.billName, (() => {
      //       this.$refs.print.show(printData, this.columnData, this.billName)
      //     }))
      //   } else {
      //     this.$refs.print.show(printData, this.columnData, this.billName)
      //   }
      // }
      // }
    },
    handlePurchaseNumberBlur(index, item) {
      let n = Number(item.purchaseNumber || 0)
      let p = Number(item.purchasePrice || 0)
      item.purchaseNumber = formatNumber(n)
      item.purchasePrice = formatPrice(p)
      item.estimatePurchaseFund = formatPrice(accMul(delcommafy(formatNumber(n)), delcommafy(formatPrice(p))))
    },
    inputFocus(e) {
      if (e) {
        e.target.select()
      }
    },
    // 触发列配置弹框
    onShowColumn() {
      // 现在的列配置
      let list = []
      this.columnData.forEach((item) => {
        let sub = item.subset
        list = list.concat(sub)
      })
      // 默认的列配置
      let defaultList = []
      let dl = this.$options.data().columnData
      dl.forEach((item) => {
        let sub = item.subset
        defaultList = defaultList.concat(sub)
      })
      console.log(defaultList)

      this.$refs.setColumnRef.loadData(list, defaultList)
    },
    // 初始化查询列配置值
    async selectTitle() {
      let obj = await this.$setColumn.selectColumn(this.url.api)
      if (obj.code === 200) {
        this.updateId = obj.updateId
        // this.columnData = obj.columnData
      } else if (obj.code === 500) {
        let id = await this.$setColumn.addColumn(this.url.api, this.$options.data().columnData)
        this.updateId = id
      }
      this.columnData.forEach((lItem, lIndex) => {
        let subList = lItem.subset
        let count = 0 //记录隐藏的个数
        subList.forEach((item, index) => {
          if (!item.zidingyiState) {
            count++
          }
        })
        lItem.show = !(count == subList.length)
      })
    },
    // 修改列配置后保存修改后的值
    async onSaveColumn(value) {
      console.log(value)

      let nIndex = 0
      this.columnData.forEach((lItem, lIndex) => {
        let subList = lItem.subset
        if (lIndex > 0) {
          nIndex += this.columnData[lIndex - 1].subset.length
        }
        let list = []
        let count = 0 //记录隐藏的个数
        subList.forEach((item, index) => {
          let nItem = value[nIndex + index]
          list.push(nItem)
          if (!nItem.zidingyiState) {
            count++
          }
        })
        lItem.subset = list
        lItem.show = !(count == list.length)
        this.columnData.splice(lIndex, 1, lItem)
      })
      console.log(this.columnData)

      this.onSaveColumnRequest()
    },
    // 修改列配置后保存修改后的值
    async onSaveColumnRequest() {
      let res = await this.$setColumn.editColumn(this.url.api, this.columnData, this.updateId)
      if (res.code == 200) {
        this.$message.success(res.message)
      } else {
        this.$message.error(res.message)
      }
    },
    //选择商品回调
    onSelectCommodityMultiple(values) {
      console.log(values)
      if (values) {
        let texts = values.map((item) => {
          return item.id
        })
        this.queryData.goodsId = texts.join(',')
        this.onHandleAnalyse()
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    treeExpandChange(val) {
      this.treeExpandAll = !this.treeExpandAll
      let nodes = this.$refs.tree.root.childNodes
      this.setNodes(nodes, this.treeExpandAll)
    },
    setNodes(list, expand) {
      list.forEach((item) => {
        item.expanded = expand
        let cr = item.childNodes
        if (cr.length > 0) {
          this.setNodes(cr, expand)
        }
      })
    },

    // 获取类别数据
    getTreeData() {
      getAction('/xghGoodsType/xghGoodsType/typeList', {}).then((res) => {
        if (res.code === 200) {
          let list = res.result
          let result = this.getTreeDataByList(list, '0', '')
          // this.treeData = result
          this.treeData = [
            {
              id: '',
              label: '全部',
              children: result,
              disabled: true
            },
          ]
          if (result.length > 0) {
            this.queryData.goodType = result[0].id
            this.$nextTick(function () {
              let node = this.$refs.tree.getNode(this.queryData.goodType)
              if (node) {
                this.$refs.tree.setCurrentKey(node.key) // 设置当前高亮节点
              }
            })
          }
        }
      })
    },
    getTreeDataByList(list, parentId, parentName) {
      let data = []
      for (let index = 0; index < list.length; index++) {
        const element = list[index]
        if (element.pid == parentId) {
          data.push({
            ...element,
            id: element.id,
            label: element.goodsTypeName,
            parentId,
            parentName,
            children: this.getTreeDataByList(list, element.id, element.companyTypeName),
          })
        }
      }
      return data
    },
    /**
     * 获取所有仓库数据
     */
    getWarehouseData() {
      getAction('/xghStorehouse/xghStorehouse/queryListByPole', {}).then((res) => {
        if (res.code === 200) {
          this.storehouseOptions = res.result || []
          this.storehouseOptions.unshift({
            storehouseName: '全部',
            id: '',
          })
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    /**
     * 初始化默认获取缓存中存储的曾经点击过的供应商数据
     */
    getCompanyList() {
      getAction('/xghCompany/xghCompany/listNoPage', {}).then((res) => {
        if (res.code === 200) {
          this.companyOptions = res.result
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    // 获取表格数据
    getTableData(page = 1) {
      console.log(page)
      let params = {
        companyId: this.queryData.companyId,
        goodsTypeIds: this.queryData.goodType,
        pageSize: this.pagesize,
        pageNo: page,
      }
      getAction(this.url.goodsList, params).then((res) => {
        if (res.code === 200) {
          this.currentPage = page || 1 // 保持和数据一致，不然分页显示不正常
          let list = res.result.records || []
          this.tableData = list.map(item => {
            item.purchaseNumber = formatNumber(item.purchaseNumber)
            item.purchasePrice = formatPrice(item.purchasePrice)
            item.estimatePurchaseFund = formatMoney(item.estimatePurchaseFund)
            item.suggestPlanProductionNumber = formatNumber(item.suggestPlanProductionNumber)
            item.suggestPurchaseNumber = formatNumber(item.suggestPurchaseNumber)

            return item
          })
          this.dataTotal = res.result.total
          this.$nextTick(() => {
            this.$refs.table.doLayout()
          })
        }else {
          this.$elMessage.error(res.message)
          this.clearData()
        }
      })
    },
    // 提醒弹框确认后操作
    onYes(mark) {
      if (mark == 'onResetAnalyse') {
        this.onHandleAnalyse()
      } else if (mark == 'onCoverPurchaseNumber') {
        // this.tableData.forEach((item, index) => {
        //   item.purchaseNumber = item.suggestPurchaseNumber
        //   this.handlePurchaseNumberBlur(index, item)
        // })
        getAction('/smartReplenishment/setSuggestCount', {
          ...this.queryData,
          goodsTypeIds: this.queryData.goodType
        }).then((res) => {
          if (res.code === 200) {
            this.getTableData()
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },
    // 提醒弹框确认后操作
    onNo(mark) {},
    // 搜索树形结构数据
    onSelectTree() {
      this.getTreeData()
    },
    // 触发树形当前节点
    handleNodeClick(data) {
      this.queryData.goodType = data.id
    },
    // 删除当前行
    onDeleteRow(row) {
      this.tipsData.tipsState = 'delete'
      this.tipsData.tipsWords = '是否确认删除?'
      this.tipsData.tipsMark = 'onDeleteRow'
      this.$refs.reminderRef.dialogVisible = true
      this.nowDataId = row.id
    },
    // 获取每页几条数据
    handleSizeChange(val) {
      this.pagesize = val
        this.getTableData()
    },
    // 获取当前第几页
    handleCurrentChange(val) {
      this.currentPage = val
      this.getTableData(val)
    },
    // 触发表格多选按钮
    handleSelectionChange(val) {
      this.batchData = val
    },
    // 合计列计算
    getSummaries(param) {
      console.log(param)

      const that = this
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (
          [
            'opNumber',
            'pending',
            'userNumber',
            'purchaseOrder',
            'productionOrder',
            'salesOrder',
            'planNumber',
            'purchaseNumber',
            'purchasePrice',
            'suggestPurchaseNumber',
          ].includes(column.property)
        ) {
          const values = data.map((item) => delcommafy(item[column.property]))
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = delcommafy(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            if (column.property === 'purchasePrice') {
              sums[index] = that.$formatPrice(sums[index])
            } else {
              sums[index] = that.$formatNumber(sums[index])
            }
          }
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
  },
}
</script>

<style lang="scss" scoped>
.basic_info {
  width: 100%;
  height: 100%;
  background: #f0f2f5;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  position: relative;
}

.info_operation_btn {
  width: 100%;
  min-height: 50px;
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  flex-shrink: 0;

  .el-button {
    width: 70px;
    height: 30px;
    text-align: center;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    border-radius: 5px;
    border: none;
    // margin-right: 0.112507rem;
    flex-shrink: 0;
    margin: 5px;
    font-weight: 400;
  }

  .el-button--default {
    color: #666;
  }

  .btn_left {
    flex: 1;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;

    ::v-deep .el-checkbox {
      margin-right: 10px;
      .el-checkbox__label {
        font-size: 12px;
        padding-left: 5px;
      }
    }
  }

  .btn_right {
    width: 50px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;

    .set_up {
      font-size: 23px;
      color: rgb(153, 153, 153);
    }
  }
}

.info_content_div {
  width: 100%;
  // height: calc(100% - 70px);
  background: #fff;
  box-sizing: border-box;
  padding: 10px;
  display: flex;

  .div_tree {
    width: 3rem;
    height: calc(100% - 50px);
    box-sizing: border-box;
    padding: 5px 0;
    border: 1px solid #e3e3e3;
    transition: all 0.3s;

    .tree_div1 {
      width: 100%;
      box-sizing: border-box;
      padding: 0 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      p {
        color: #666666;
        font-size: 12px;
      }
    }

    .tree_input {
      width: 100%;
      height: 30px;
      margin-top: 10px;
      box-sizing: border-box;
      padding: 0 10px;

      p {
        width: 100%;
        height: 30px;
        margin: 0;
        box-sizing: border-box;
        border: 1px solid #dddddd;
        display: flex;
        align-items: center;
        position: relative;

        input {
          width: 100%;
          box-sizing: border-box;
          padding: 0 3px;
          height: 28px;
          border: none;
          font-size: 12px;

          &:focus {
            outline: none;
          }
        }

        span {
          position: absolute;
          right: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 25px;
          height: 28px;
          background: #fff;

          .el-icon-search {
            font-size: 16px;
            color: rgb(211, 211, 211);
          }
        }
      }
    }

    .tree_structure {
      width: 100%;
      height: calc(100% - 70px);
      box-sizing: border-box;
      padding: 0 0.168761rem;
      margin-top: 0.131258rem;
      overflow: auto;

      ::v-deep .el-tree {
        width: 100%;

        .tree_node {
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: space-between;

          span {
            font-size: 12px;
          }

          .show_nodex {
            font-size: 0.25rem;
            display: flex;
            align-items: center;

            i {
              margin-right: 0.15rem;
              font-weight: 600;
            }

            .el-icon-circle-plus-outline {
              color: #1993fb;
            }

            .el-icon-edit-outline {
              color: #1993fb;
            }

            .el-icon-delete {
              color: #ff2626;
            }
          }
        }

        .el-tree-node__children {
          .el-tree-node__label {
            color: #666;
            font-weight: normal;
          }
        }

        .el-tree-node__label {
          font-size: 12px;
          font-weight: 600;
        }

        .is-current {
          .el-tree-node__content {
            background-color: #e6f7ff;
          }
        }

        .el-tree-node__content > .el-tree-node__expand-icon {
          padding-left: 0;
        }
      }
    }
  }

  .div_table {
    width: calc(100% - 3rem);
    height: 100%;
    margin-left: 0.187512rem;
    display: flex;
    flex-direction: column;
    // justify-content: space-between;
    transition: all 0.3s;

    .table_content {
      height: calc(100% - 50px);
      overflow: hidden;
      overflow-x: scroll;

      ::v-deep .el-table {
        border: 1px solid #e3e3e3;
        border-bottom: none;
        box-sizing: border-box;

        th {
          .el-input {
            .el-input__inner {
              padding-left: 3px;
              border: #707070 solid 1px;
              border-radius: 0;
            }
          }
        }
        td {
          .el-input {
            .el-input__inner {
              border: unset;
              margin: 2px;
              padding: 0 3px;
              height: 26px;
              line-height: 26px;
              width: calc(100% - 4px);
              border-radius: 0;
            }
          }
        }

        th,
        td {
          padding: 0;
          color: #666;
          box-sizing: border-box;
          border-right: 1px solid #e3e3e3;

          .cell {
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            padding: 0;
          }
        }
        .el-table__header {
          tr {
            &:last-child {
              th {
                background: rgb(237, 237, 237) !important;
              }
            }
          }
        }

        .el-table__footer {
          td {
            border: unset;
            background: white;
          }
        }

        // .el-checkbox {
        //   .is-indeterminate {
        //     .el-checkbox__inner {
        //       color: #1b93f9;
        //       background-color: #1b93f9;
        //       border-color: #1b93f9;
        //     }
        //   }
        // }

        // .el-icon-edit-outline {
        //   font-size: 20px;
        //   color: #1b93f9;
        //   margin-right: 0.037502rem;
        // }

        // .el-icon-delete {
        //   font-size: 20px;
        //   color: #ff2626;
        //   margin-left: 0.037502rem;
        // }

        // .el-table__body tr:hover > td {
        //   background: #e3f6ff;
        // }

        // .el-table__footer-wrapper {
        //   td {
        //     background: #f4f4f4;
        //     border: none;
        //   }
        // }

        //滚动条的宽度
        ::-webkit-scrollbar {
          width: 8px;
          height: 10px;
          background-color: #e5e5e5;
        }

        //滚动条的滑块
        ::-webkit-scrollbar-thumb {
          background-color: #c9c9c9;
        }
      }
    }

    .total_record {
      width: 100%;
      height: 30px;
      box-sizing: border-box;
      padding: 0 0.25rem;
      border: 1px solid #e3e3e3;
      border-top: none;
      background: #f4f4f4;
      display: flex;

      p {
        margin: 0;
        line-height: 30px;
        padding-right: 0.25rem;
        font-size: 12px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #666666;
      }
    }

    .table_pagination {
      width: 100%;
      height: 50px;
      box-sizing: border-box;
      padding: 0.168761rem 0;
      display: flex;

      .pagination_div {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        ::v-deep .el-pagination {
          padding: 0;
          height: 30px;

          .el-pagination__sizes {
            margin: 0;

            .el-input {
              margin-right: 0;
            }
          }
        }
      }
    }
  }

  .new_div_table_width {
    width: calc(100% - 4.31277rem);
  }
}

.disabled_button {
  background: #cbced3 !important;
  color: #666 !important;
}
.pretend_view {
  padding: 0 10px;
  border-radius: 5px;
  height: 30px;
  line-height: 30px;
  margin-right: 10px;
  font-size: 12px;
  flex-shrink: 0;
  margin: 5px;
  min-width: 68px;
  text-align: center;
  background-color: #fff;
  cursor: pointer;
}
.location {
  .extendView {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100px;
  }

  .dialog_bottom {
    width: 100%;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;

    .el-button {
      width: 80px;
    }
  }
  ::v-deep .el-dialog {
    .el-dialog__header {
      border-bottom: #ededed solid 1px;
      padding: 10px 15px;
    }
    .el-dialog__body {
      padding: 10px 30px;
    }
  }
}
</style>

